import BaseService from './base';
import Sequelize from 'sequelize';
const Op = Sequelize.Op;

export default class MessageService extends BaseService {
  constructor({ messageDao }) {
    super();
    this.messageDao = messageDao
  }

  async getMessageAll (msg) {
    const [err, list] = await this.messageDao.getMessageAll({
      attributes: ['t_tell'],
      where: {
        mark: {[Op.ne]: msg.mark}
      }
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', list);
  }

  async getMessageList(msg) {
    const [err, count, rows] = await this.messageDao.getMessageList({
      where: {
        t_tell: msg.t_tell === '' ? {
          [Op.ne]: null
        } : msg.t_tell,
        mark: {[Op.ne]: msg.mark}
      },
      limit: msg.limit,
      offset: msg.limit * (msg.offset - 1),
      distinct: true
    });
    if (err) {
      return this.fail('获取列表失败', null, err);
    }
    return this.success('查询成功', count, rows);
  }

  async addMessage(msg) {
    const [exsitErr, itemExsit] = await this.messageDao.findOne({
      where: {
        t_tell: msg.t_tell
      }
    });
    if (exsitErr) {
      return this.fail('添加失败', null, exsitErr);
    }
    if (itemExsit) {
      return this.fail('已存在');
    }
    const [addErr] = await this.messageDao.addMessage(msg);
    if (addErr) {
      return this.fail('添加失败', null, addErr);
    }
    return this.success('添加成功')
  }

  async delMessage(msg) {
    const [err, updateMessage] = await this.messageDao.update(msg, {
      where: {
        id: msg.id
      }
    });
    if (err) {
      return this.fail('删除失败');
    }
    return this.success('删除成功');
  }

  async updateMessage(msg) {
    const [err, updateMessage] = await this.messageDao.update(msg, {
      where: {
        id: msg.id
      }
    });
    if (err) {
      return this.fail('更新失败');
    }
    return this.success('更新成功');
  }
}